﻿using AgencyManagerSystem.AsmType;
using AgencyManagerSystem.Common;
using AgencyManagerSystem.Core;
using AgencyManagerSystem.DataFetcher;
using AgencyManagerSystem.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Net;

namespace AgencyManagerSystem.Controllers
{
    public class ModuleController : MyControllerBase
    {
        ModuleManager manager;
        ModuleFetcher fetcher;
        public ModuleController() : base()
        {
            this.manager = new ModuleManager();
            this.fetcher = new ModuleFetcher();
        }
        [HttpGet]
        [Authorize]
        public AsmArray<ModuleWithRoleModel> List()
        {
            AsmArray<ModuleWithRoleModel> result = new AsmArray<ModuleWithRoleModel>();
            if (profile == null)
            {
                LogHelper.Err(this.GetType(), "LIST:系统内部异常，Profile为空");
                result.Message = "系统内部异常";
                result.Result = AmsCode.InnError;
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
            else
            {
                LogHelper.Log(this.GetType(), String.Format("LIST:用户{0}:{1}正在列出功能清单",profile.UserId,RequestIp));
                result.Data = fetcher.ListByUserWithRole(profile.UserId, profile.Domain);
                result.Message = "操作成功";
                result.Result = AmsCode.Succ;
            }
            LogHelper.Debug(this.GetType(), String.Format("LIST:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));

            //DBHelper.Commit(tranCode, result.Result != AmsCode.Succ); 
            DBHelper.Commit(true);//只读类接口任何时候都要求commit,因为有可能产生数据库操作记录
            return result;
        }

        [HttpGet]
        [Authorize]
        public AsmArray<ModuleModel> ListByKeyword(string keyword)
        {
            AsmArray<ModuleModel> result = new AsmArray<ModuleModel>();
            if (profile == null)
            {
                LogHelper.Err(this.GetType(), "LISTBYKEYWORD:系统内部异常，Profile为空");
                result.Message = "系统内部异常";
                result.Result = AmsCode.InnError;
                Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
            else
            {
                LogHelper.Log(this.GetType(), String.Format("LISTBYKEYWORD:用户{0}:{1}正在列出功能清单", profile.UserId, RequestIp));
                Condition condition = new Condition() { Key = "Name", Op = "Like", Value = "%" + keyword + "%" };
                result.Data = fetcher.List(new Condition[] { condition });
                result.Message = "操作成功";
                result.Result = AmsCode.Succ;
            }
            LogHelper.Debug(this.GetType(), String.Format("LISTBYKEYWORD:[RSP|{1}]{0}", Util.ConvertToJson(result), RequestIp));

            //DBHelper.Commit(tranCode, result.Result != AmsCode.Succ); 
            DBHelper.Commit(true);//只读类接口任何时候都要求commit,因为有可能产生数据库操作记录
            return result;
        }
    }
}